package com.gitee.easyopen;

import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.Assert;

import com.auth0.jwt.interfaces.Claim;
import com.gitee.easyopen.auth.OpenUser;
import com.gitee.easyopen.jwt.JwtService;
import com.gitee.easyopen.message.Errors;

/**
 * 应用上下文,方便获取信息
 * 
 * @author tanghc
 *
 */
public class ApiContext {
    private static ThreadLocal<ApiParam> param = new InheritableThreadLocal<>();
    private static ThreadLocal<OpenUser> tokenUser = new InheritableThreadLocal<>();
    private static ThreadLocal<Map<String, Claim>> jwtData = new InheritableThreadLocal<>();
    private static ApiConfig apiConfig;

    /**
     * 创建JWT
     * @param appKey
     * @param data
     * @return
     */
    public static String createJwt(Map<String, String> data) {
        Assert.notNull(apiConfig, "apiConfig尚未初始化");
        JwtService jwtService = apiConfig.getJwtService();
        return jwtService.createJWT(data);
    }

    /**
     * 返回jwt数据,没有返回null
     * 
     * @return
     */
    public static Map<String, Claim> getJwtData() {
        return jwtData.get();
    }

    public static void setJwtData(Map<String, Claim> data) {
        jwtData.set(data);
    }

    /**
     * 获取accessToken对应的用户
     * 
     * @return
     */
    public static OpenUser getAccessTokenUser() {
        OpenUser user = tokenUser.get();
        if (user == null) {
            throw Errors.UNSET_ACCESS_TOKEN.getException();
        }
        return user;
    }

    public static void setAccessTokenUser(OpenUser openUser) {
        tokenUser.set(openUser);
    }

    /**
     * 获取HttpServletRequest
     * 
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        ApiParam apiParam = getApiParam();
        if (apiParam == null) {
            return null;
        }
        return apiParam.fatchRequest();
    }

    /**
     * 获取本地化
     * 
     * @return Locale
     */
    public static Locale getLocal() {
        HttpServletRequest req = getRequest();
        if (req == null) {
            return Locale.SIMPLIFIED_CHINESE;
        }
        return req.getLocale();
    }

    public static void setApiParam(ApiParam apiParam) {
        param.set(apiParam);
    }

    /**
     * 获取系统参数
     * 
     * @return 返回ApiParam
     */
    public static ApiParam getApiParam() {
        return param.get();
    }

    public static ApiConfig getApiConfig() {
        return apiConfig;
    }

    public static void setApiConfig(ApiConfig apiConfig) {
        ApiContext.apiConfig = apiConfig;
    }

}
